import pyaudio
import json
import threading
from vosk import Model, KaldiRecognizer

# 语音采样率和每次读取数据大小（缓冲区大小）
RATE = 16000
CHUNK = 4000

# 加载 Vosk 模型，模型路径为当前目录下的 "vosk-model-small-cn-0.22"
model = Model("vosk-model-cn-0.22")

# 初始化 pyaudio
p = pyaudio.PyAudio()
stream = p.open(format=pyaudio.paInt16,
                channels=1,
                rate=RATE,
                input=True,
                frames_per_buffer=CHUNK)
stream.start_stream()

print("按回车键开始录音...")
input()  # 用户按回车开始录音

print("开始录音，按回车键结束录音...")
# 标志录音状态
recording = True
frames = []

# 定义录音线程函数
def record_audio():
    global recording, frames
    while recording:
        try:
            data = stream.read(CHUNK, exception_on_overflow=False)
            frames.append(data)
        except Exception as e:
            print("录音过程中出错：", e)
            break

# 开启录音线程
record_thread = threading.Thread(target=record_audio)
record_thread.start()

# 等待用户按回车结束录音
input()
recording = False
record_thread.join()
print("录音结束，正在进行识别...")

# 创建识别器
rec = KaldiRecognizer(model, RATE)
# 将录音数据分块送入识别器
for data in frames:
    rec.AcceptWaveform(data)

# 获取最终识别结果
result = rec.Result()
result_dict = json.loads(result)
text = result_dict.get("text", "")

print("识别结果：", text)

# 清理资源
stream.stop_stream()
stream.close()
p.terminate()
